package com.njworkorder.HTSingleLogin;

import cn.microvideo.qsc.client.entity.Role;
import cn.microvideo.qsc.client.entity.User;
import cn.microvideo.qsc.client.entity.xml.ParentRoles;
import cn.microvideo.qsc.client.entity.xml.Roles;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

import static com.njworkorder.HTSingleLogin.TokenService.MILLIS_MINUTE;

/**
 * 用户验证处理
 *
 * @author ht
 */
@Service("CasUserDetailsServiceImpl")
public class CasUserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(CasUserDetailsServiceImpl.class);

    private final int expireTime;
    private final IQsUserService qsUserService;
    private final SysPermissionService permissionService;

    @Autowired
    public CasUserDetailsServiceImpl(
            @Value("${token.expireTime}") int expireTime,
            @Qualifier("qsUserServiceImpl") IQsUserService qsUserService,
            SysPermissionService permissionService) {
        this.expireTime = expireTime;
        this.qsUserService = qsUserService;
        this.permissionService = permissionService;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
            log.info("cas用户查询:{}",username);
            User user =  qsUserService.selectZgUserByUserName(username);

            log.info("cas用户信息:{}",user);

            if (StringUtils.isNull(user))
            {
                log.info("登录用户：{} 不存在.", username);
                throw new ServiceException(MessageUtils.message("user.not.exists"));
            }
            QsUser qsUser = new QsUser();
            qsUser.genBody(user);

            log.info("cas当前认证用户信息:{}",qsUser);

            qsUser.setShowTitle(false);
            return createLoginUser(qsUser);

    }

    public UserDetails createLoginUser(QsUser user)
    {
//        LoginUser loginUser = new LoginUser(user.getUid(), user.getOuid(), user.getOid(), user, permissionService.getMenuPermission(user), Boolean.FALSE);
        LoginUser loginUser = new LoginUser(user.getUid(), user.getOuid(), user.getOid(), user, new HashSet<>(), Boolean.FALSE);
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        loginUser.setLocal(false);

        log.info("cas认成功的用户UserDetails:{}",loginUser);

        return loginUser;
    }
}
